/*
 * Created by SharpDevelop.
 * User: phtrung
 * Date: 6/24/2008
 * Time: 11:05 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Data;
using System.Collections;

namespace QuickSearch
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public class MainForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.StatusBar statusBar1;
		private System.Windows.Forms.SaveFileDialog saveFileDialog1;
		private System.Windows.Forms.TextBox path;
		private System.Windows.Forms.CheckBox cb_opt2b;
		private System.Windows.Forms.ListBox result;
		private System.Windows.Forms.Button button2;
		private System.Windows.Forms.CheckBox cb_opt2a;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem menuItem2;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
		private System.Windows.Forms.CheckBox cb_opt1;
		private System.Windows.Forms.ContextMenu contextMenu1;
		private System.Windows.Forms.Panel panel3;
		private System.Windows.Forms.Panel panel2;
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.TextBox keyword;
		private System.Windows.Forms.GroupBox groupBox1;
		
		Thread currentThread;
		DataSet ds;
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
			currentThread = new Thread(new ThreadStart(doSearch));
			ds = new DataSet();
			ds.Tables.Add("Table1");
			ds.Tables[0].Columns.Add("Files");
			ds.Tables[0].Columns.Add("Paths");
			
		}
		
		[STAThread]
		public static void Main(string[] args)
		{
			Application.Run(new MainForm());
		}
		
		#region Windows Forms Designer generated code
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent() {
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.keyword = new System.Windows.Forms.TextBox();
			this.button1 = new System.Windows.Forms.Button();
			this.panel1 = new System.Windows.Forms.Panel();
			this.panel2 = new System.Windows.Forms.Panel();
			this.panel3 = new System.Windows.Forms.Panel();
			this.contextMenu1 = new System.Windows.Forms.ContextMenu();
			this.cb_opt1 = new System.Windows.Forms.CheckBox();
			this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.menuItem2 = new System.Windows.Forms.MenuItem();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.groupBox2 = new System.Windows.Forms.GroupBox();
			this.cb_opt2a = new System.Windows.Forms.CheckBox();
			this.button2 = new System.Windows.Forms.Button();
			this.result = new System.Windows.Forms.ListBox();
			this.cb_opt2b = new System.Windows.Forms.CheckBox();
			this.path = new System.Windows.Forms.TextBox();
			this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
			this.statusBar1 = new System.Windows.Forms.StatusBar();
			this.groupBox1.SuspendLayout();
			this.panel1.SuspendLayout();
			this.panel2.SuspendLayout();
			this.groupBox2.SuspendLayout();
			this.SuspendLayout();
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.Add(this.cb_opt1);
			this.groupBox1.Controls.Add(this.panel1);
			this.groupBox1.Controls.Add(this.panel3);
			this.groupBox1.Controls.Add(this.panel2);
			this.groupBox1.Controls.Add(this.cb_opt2a);
			this.groupBox1.Controls.Add(this.cb_opt2b);
			this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
			this.groupBox1.Location = new System.Drawing.Point(0, 0);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(688, 104);
			this.groupBox1.TabIndex = 0;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Search Detail";
			// 
			// keyword
			// 
			this.keyword.Dock = System.Windows.Forms.DockStyle.Fill;
			this.keyword.Location = new System.Drawing.Point(0, 0);
			this.keyword.Name = "keyword";
			this.keyword.Size = new System.Drawing.Size(682, 22);
			this.keyword.TabIndex = 1;
			this.keyword.Text = "";
			// 
			// button1
			// 
			this.button1.Dock = System.Windows.Forms.DockStyle.Right;
			this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.button1.Location = new System.Drawing.Point(594, 0);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(88, 20);
			this.button1.TabIndex = 3;
			this.button1.Text = "Browse";
			this.button1.Click += new System.EventHandler(this.Button1Click);
			// 
			// panel1
			// 
			this.panel1.Controls.Add(this.button1);
			this.panel1.Controls.Add(this.path);
			this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
			this.panel1.Location = new System.Drawing.Point(3, 46);
			this.panel1.Name = "panel1";
			this.panel1.Size = new System.Drawing.Size(682, 20);
			this.panel1.TabIndex = 7;
			// 
			// panel2
			// 
			this.panel2.Controls.Add(this.button2);
			this.panel2.Controls.Add(this.keyword);
			this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
			this.panel2.Location = new System.Drawing.Point(3, 18);
			this.panel2.Name = "panel2";
			this.panel2.Size = new System.Drawing.Size(682, 20);
			this.panel2.TabIndex = 8;
			// 
			// panel3
			// 
			this.panel3.Dock = System.Windows.Forms.DockStyle.Top;
			this.panel3.Location = new System.Drawing.Point(3, 38);
			this.panel3.Name = "panel3";
			this.panel3.Size = new System.Drawing.Size(682, 8);
			this.panel3.TabIndex = 9;
			// 
			// contextMenu1
			// 
			this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
						this.menuItem1,
						this.menuItem2,
						this.menuItem3});
			// 
			// cb_opt1
			// 
			this.cb_opt1.Checked = true;
			this.cb_opt1.CheckState = System.Windows.Forms.CheckState.Checked;
			this.cb_opt1.Location = new System.Drawing.Point(8, 72);
			this.cb_opt1.Name = "cb_opt1";
			this.cb_opt1.Size = new System.Drawing.Size(144, 24);
			this.cb_opt1.TabIndex = 10;
			this.cb_opt1.Text = "include subfolders";
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 0;
			this.menuItem1.Text = "Open File";
			this.menuItem1.Click += new System.EventHandler(this.MenuItem1Click);
			// 
			// menuItem2
			// 
			this.menuItem2.Index = 1;
			this.menuItem2.Text = "Open Folder";
			this.menuItem2.Click += new System.EventHandler(this.MenuItem2Click);
			// 
			// menuItem3
			// 
			this.menuItem3.Index = 2;
			this.menuItem3.Text = "Save list of files";
			this.menuItem3.Click += new System.EventHandler(this.MenuItem3Click);
			// 
			// groupBox2
			// 
			this.groupBox2.Controls.Add(this.result);
			this.groupBox2.Controls.Add(this.statusBar1);
			this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
			this.groupBox2.Location = new System.Drawing.Point(0, 104);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(688, 438);
			this.groupBox2.TabIndex = 2;
			this.groupBox2.TabStop = false;
			this.groupBox2.Text = "Result";
			// 
			// cb_opt2a
			// 
			this.cb_opt2a.Location = new System.Drawing.Point(184, 72);
			this.cb_opt2a.Name = "cb_opt2a";
			this.cb_opt2a.Size = new System.Drawing.Size(136, 24);
			this.cb_opt2a.TabIndex = 11;
			this.cb_opt2a.Text = "Search file only";
			this.cb_opt2a.CheckedChanged += new System.EventHandler(this.Cb_opt2aCheckedChanged);
			// 
			// button2
			// 
			this.button2.Dock = System.Windows.Forms.DockStyle.Right;
			this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.button2.Location = new System.Drawing.Point(594, 0);
			this.button2.Name = "button2";
			this.button2.Size = new System.Drawing.Size(88, 20);
			this.button2.TabIndex = 4;
			this.button2.Text = "Search";
			this.button2.Click += new System.EventHandler(this.Button2Click);
			// 
			// result
			// 
			this.result.BorderStyle = System.Windows.Forms.BorderStyle.None;
			this.result.ContextMenu = this.contextMenu1;
			this.result.Dock = System.Windows.Forms.DockStyle.Fill;
			this.result.Font = new System.Drawing.Font("Consolas", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.result.HorizontalScrollbar = true;
			this.result.ItemHeight = 18;
			this.result.Location = new System.Drawing.Point(3, 18);
			this.result.Name = "result";
			this.result.Size = new System.Drawing.Size(682, 378);
			this.result.TabIndex = 5;
			this.result.DoubleClick += new System.EventHandler(this.MenuItem1Click);
			// 
			// cb_opt2b
			// 
			this.cb_opt2b.Location = new System.Drawing.Point(328, 72);
			this.cb_opt2b.Name = "cb_opt2b";
			this.cb_opt2b.Size = new System.Drawing.Size(144, 24);
			this.cb_opt2b.TabIndex = 11;
			this.cb_opt2b.Text = "Search folder only";
			this.cb_opt2b.CheckedChanged += new System.EventHandler(this.Cb_opt2aCheckedChanged);
			// 
			// path
			// 
			this.path.Dock = System.Windows.Forms.DockStyle.Fill;
			this.path.Location = new System.Drawing.Point(0, 0);
			this.path.Name = "path";
			this.path.Size = new System.Drawing.Size(682, 22);
			this.path.TabIndex = 2;
			this.path.Text = "C:\\";
			// 
			// saveFileDialog1
			// 
			this.saveFileDialog1.Filter = "txt files(*.txt)|*.txt|All files(*.*)|*.*";
			// 
			// statusBar1
			// 
			this.statusBar1.Location = new System.Drawing.Point(3, 413);
			this.statusBar1.Name = "statusBar1";
			this.statusBar1.Size = new System.Drawing.Size(682, 22);
			this.statusBar1.TabIndex = 6;
			this.statusBar1.Text = "Ready";
			// 
			// MainForm
			// 
			this.AcceptButton = this.button2;
			this.AutoScaleBaseSize = new System.Drawing.Size(7, 15);
			this.ClientSize = new System.Drawing.Size(688, 542);
			this.Controls.Add(this.groupBox2);
			this.Controls.Add(this.groupBox1);
			this.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "MainForm";
			this.Text = "Quick Search";
			this.Closing += new System.ComponentModel.CancelEventHandler(this.MainFormClosing);
			this.Load += new System.EventHandler(this.MainFormLoad);
			this.groupBox1.ResumeLayout(false);
			this.panel1.ResumeLayout(false);
			this.panel2.ResumeLayout(false);
			this.groupBox2.ResumeLayout(false);
			this.ResumeLayout(false);
		}
		#endregion
		void Button1Click(object sender, System.EventArgs e)
		{
			if(folderBrowserDialog1.ShowDialog().ToString() == "OK" ){
				path.Text = folderBrowserDialog1.SelectedPath;
			}
		}
		
		
		
		void Button2Click(object sender, System.EventArgs e)
		{
			if(keyword.Text.Trim().Length>0)
			if(Directory.Exists(path.Text))
			if(button2.Text == "Search"){
				setStatus(1);
				currentThread = new Thread(new ThreadStart(doSearch));
				currentThread.Start();
			}else{
				setStatus(0);
				currentThread.Abort();				
			}
			else statusBar1.Text = "Ready - selected path is not existed!";
			else statusBar1.Text = "Ready - nothing to search!";
		}
		
		
		ArrayList listItemValues = new ArrayList();
		public void doSearch(){
			result.Items.Clear();
			listItemValues.Clear();
			foreach( string filter in keyword.Text.Split(';')){				
				foreach(string file in getFileList(path.Text, filter, cb_opt1.Checked)){
					result.Items.Add( spaceLeft(file.Split('\\')[file.Split('\\').Length-1], 40) + "\t" +  file );
					listItemValues.Add(file);
				}
			}
			setStatus(2);
		}
		
		public void setStatus(int state){
			
			if(state == 0){
				this.Text = "Quick Search";
				button2.Text = "Search";
				statusBar1.Text = "Ready";
				path.ReadOnly = keyword.ReadOnly = false;
				button1.Enabled = true;
			}
			
			if(state == 1){
				this.Text = "Quick Search - Searching ["+keyword.Text+"] in " + path.Text;
				statusBar1.Text = "Searching....";
				button2.Text = "Stop";
				path.ReadOnly = keyword.ReadOnly = true;
				button1.Enabled = false;
			}
			
			if(state == 2){
				this.Text = "Quick Search - Done ["+result.Items.Count+" result(s)]";
				statusBar1.Text = "Done - found "+result.Items.Count+" files/folder";
				button2.Text = "Search";
				path.ReadOnly = keyword.ReadOnly = false;
				button1.Enabled = true;
			}
		}
		
		
		public string[] getFileList(string path, string filter, bool includeSubfolder){
			string[] files = new string[0];
			string[] folers = new string[0];;
			if(cb_opt2a.Checked)				
				files  = Directory.GetFiles( path, filter );
			else if(cb_opt2b.Checked)				
				folers = Directory.GetDirectories( path, filter );			
			else{
				files  = Directory.GetFiles( path, filter );
				folers = Directory.GetDirectories( path, filter );
			}
					
			
			ListBox temp = new ListBox();
			temp.Items.AddRange(files);
			temp.Items.AddRange(folers);
			
			if(filter.IndexOf("*") == -1){
				files  = Directory.GetFiles( path, "*" + filter + "*" );
				folers = Directory.GetDirectories( path, "*" + filter + "*" );
				temp.Items.AddRange(files);
				temp.Items.AddRange(folers);
			}
			
			if(includeSubfolder){
				string[] directories    = Directory.GetDirectories( path );	
				for(int i=0; i<directories.Length; i++){				
					string[] subFiles = getFileList( directories[i], filter, true );
					temp.Items.AddRange(subFiles);
				}
			}
			files = new string[temp.Items.Count];
			temp.Items.CopyTo( files, 0 );
			return files;
		}
		
		
		void MenuItem1Click(object sender, System.EventArgs e)
		{
			try{
			if(result.SelectedIndex >= 0)				
				Process.Start( listItemValues[result.SelectedIndex]+"", "" );
			}catch(Exception ex){
				if(ex.Message.IndexOf("No") == 0){
					ProcessStartInfo psi = new ProcessStartInfo(listItemValues[result.SelectedIndex]+"");
					psi.UseShellExecute = true; // u need this
					psi.ErrorDialog = true; // and this which launch the OpenWith dialog
					Process.Start(psi);					
				}
			}
		}
		
		void MenuItem2Click(object sender, System.EventArgs e)
		{
			if(result.SelectedIndex >= 0){
				string file     = listItemValues[result.SelectedIndex]+"";				
				Process.Start( "EXPLORER.EXE", "/select,\"" + file +"\"" );
			}
		}
		
		void MainFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
		{			
			currentThread.Abort();
		}		
		
		string spaceLeft(string src, int length){
			for(int i=src.Length;i< length ; i+=8 ){
				src+="\t";
			}
			return src ;
		}
		void MainFormLoad(object sender, System.EventArgs e)
		{
			keyword.Select();
			if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)){
	    		string content = Clipboard.GetDataObject().GetData(DataFormats.UnicodeText, true).ToString();
	    		if(content.IndexOf(":\\") == 1) path.Text = content;
			}
		}
		
		void Cb_opt2aCheckedChanged(object sender, System.EventArgs e)
		{
			CheckBox tmp = (CheckBox)sender;
			if(tmp.Checked)
			if(tmp.Text.IndexOf("file") > 0) cb_opt2b.Checked = false;
			else cb_opt2a.Checked = false;			
		}
		
		void MenuItem3Click(object sender, System.EventArgs e)
		{			
			string content = "";
			if(saveFileDialog1.ShowDialog()+"" == "OK"){
				for(int i=0;i<listItemValues.Count;i++){
					content+= listItemValues[i].ToString().Substring(listItemValues[i].ToString().LastIndexOf("\\")+1);
					content+= "|" + listItemValues[i] + "\r\n";
				}
				writeFile(saveFileDialog1.FileName, content);
				MessageBox.Show("Save list files done.");
			}
			
		}
		
		public static string readFile(string file){
			if(File.Exists(file)){
				StreamReader sr = new StreamReader(file);
				string content = sr.ReadToEnd();
				sr.Close();
				return content;
			}
			return "";
		}
		
		public static void writeFile(string file, string content){			
			StreamWriter sw = new StreamWriter(file);
			sw.Write(content);
			sw.Flush();
			sw.Close();			
		}
		
	}
}
